package globalVisionEntertainment.nba.batch;

import globalVisionEntertainment.nba.EspnGameRecord;
import gqqnbig.SystemHelper;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.Callable;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Program
{
	public static boolean hasError = false;

	static int sleepInterval = 2000;

	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

	static Callable<PrintStream> getPrintStream = new Callable<PrintStream>()
	{
		@Override
		public PrintStream call() throws Exception
		{
			Program.hasError = true;
			return System.out;
		}
	};

	public static void main(String[] args) throws IOException, InterruptedException, ParseException
	{
		TimeZone.setDefault(new SimpleTimeZone(0, "UTC"));

		// if (args.length > 0)
		// {
		// try
		// {
		// sleepInterval = Integer.parseInt(args[0]) * 1000;
		// }
		// catch (NumberFormatException e)
		// {
		// System.out.println("-h, --help, /? \t\t Show help screen.");
		// System.out.println("number \t\t Specify the sleep time in seconds after imported a game. ");
		// System.out
		// .println("\t\t\t Importing games too fast may incur a block by the website. Default: 2 seconds.");
		// return;
		// }
		// }

		File file = new File(".");
		String path = file.getCanonicalPath();
		System.out.println(path);

		// System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
		// System.out.println(StreamReaderThread.class.getClassLoader().getResource(""));
		// System.out.println(ClassLoader.getSystemResource(""));
		// System.out.println(StreamReaderThread.class.getResource(""));
		// System.out.println(StreamReaderThread.class.getResource("/"));
		// System.out.println(new File("import.bat").getAbsolutePath());
		// System.out.println(System.getProperty("user.dir"));

		Calendar earlyDate = Calendar.getInstance();
		earlyDate.setTimeZone(new SimpleTimeZone(0, "UTC"));
		Calendar laterDate = Calendar.getInstance();
		earlyDate.setTimeZone(new SimpleTimeZone(0, "UTC"));
		if (args.length == 0)
		{
			// import from now to one year ago.
			earlyDate.add(Calendar.YEAR, -1);
		}
		else if (args.length == 2)
		{
			earlyDate.setTime(dateFormat.parse(args[0]));
			laterDate.setTime(dateFormat.parse(args[1]));
		}
		else
		{
			System.out.println("import from now to one year ago, \n or import from one date to another date.");
			System.out.println("date format is YYYYMMdd, for example 20140302.");
		}

		try
		{
			run(earlyDate, laterDate);
		}
		finally
		{
			System.out.printf("Imported from %s to %s.\n", dateFormat.format(earlyDate.getTime()), dateFormat.format(laterDate.getTime()));
		}
	}

	private static void run(Calendar earlyDate, Calendar laterDate) throws IOException, InterruptedException
	{
		File scriptFile = new File(SystemHelper.getAppPath(Program.class), "PlayerStatisticReader.jar");

		while (earlyDate.before(laterDate) || earlyDate.equals(laterDate))
		{
			String url = "http://espn.go.com/nba/schedule/_/date/" + dateFormat.format(laterDate.getTime());

			System.out.println(url);

			Document document = EspnGameRecord.parseWebDocument(url);

			Elements elements = document.select(".mod-content tr>td:eq(0)>a[href*=boxscore?id=]");

			for (int i = elements.size() - 1; i >= 0; i--)
			{
				Element element = elements.get(i);

				String gameId = element.attr("href");
				gameId = gameId.substring(gameId.indexOf("id=") + 3);
				ProcessBuilder processBuilder;
				// if (System.getProperty("os.name").equals("Mac OS X"))
				processBuilder = new ProcessBuilder("java", "-jar", scriptFile.getAbsolutePath(), gameId);
				// else
				// processBuilder = new ProcessBuilder(scriptFile.getAbsolutePath(), gameId);

				Process p = processBuilder.start();

				new Thread(new gqqnbig.StreamReaderThread(p.getInputStream(), System.out)).start();

				new Thread(new gqqnbig.ErrorStreamReaderThread(p.getErrorStream(), getPrintStream)).start();

				p.waitFor();

				if (hasError)
				{
					System.err.println("Error occured in execution.");
					hasError = false;
					// return;
				}

				Thread.sleep(sleepInterval);
				// break;

			}
			laterDate.add(Calendar.DATE, -7);
		}
	}

}
